package cn.whdream.datastructure.tree;
/**
 * 
 * @author admin
 * 数组方式存储树
 */
public class ArrBinaryTreeDemo {
	public static void main(String[] args) {
		int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
		//创建一个 ArrBinaryTree
		ArrBinaryTree arrBinaryTree = new ArrBinaryTree(arr);
		arrBinaryTree.preOrder(); // 1,2,4,5,3,6,7
		System.out.println("中序遍历");
		arrBinaryTree.infixOrder();
		System.out.println("后序遍历");
		arrBinaryTree.postOrder();
	}
	/**
	 * 
	 * @author admin
	 * 数组存储
	 */
	private static class ArrBinaryTree{
		private int[] arr;

		public ArrBinaryTree(int[] arr) {
			super();
			this.arr = arr;
		}
		
		public void preOrder() {
			preOder(0);
		}
		
		public void infixOrder() {
			infixOrder(0);
		}
		
		public void postOrder() {
			postOrder(0);
		}
		
		private void postOrder(int index) {
			if (arr == null || arr.length == 0) {
				System.out.println("数组为空");
				return;
			}
			int length = arr.length;
			//左边节点
			int nextNodeIndex = 2 * index + 1;
			if(length > nextNodeIndex) {
				preOder(nextNodeIndex);
			}
		
			//右边节点
			nextNodeIndex = 2 * index + 2;
			if (length > nextNodeIndex) {
				preOder(nextNodeIndex);
			}
			
			System.out.println(arr[index]);
		}

		private void infixOrder(int index) {
			if (arr == null || arr.length == 0) {
				System.out.println("数组为空");
				return;
			}
			int length = arr.length;
			//左边节点
			int nextNodeIndex = 2 * index + 1;
			if(length > nextNodeIndex) {
				preOder(nextNodeIndex);
			}
			System.out.println(arr[index]);
			//右边节点
			nextNodeIndex = 2 * index + 2;
			if (length > nextNodeIndex) {
				preOder(nextNodeIndex);
			}
			
		}

		private void preOder(int index) {
			if (arr == null || arr.length == 0) {
				System.out.println("数组为空");
				return;
			}
			int length = arr.length;
			System.out.println(arr[index]);
			//左边节点
			int nextNodeIndex = 2 * index + 1;
			if(length > nextNodeIndex) {
				preOder(nextNodeIndex);
			}
			//右边节点
			nextNodeIndex = 2 * index + 2;
			if (length > nextNodeIndex) {
				preOder(nextNodeIndex);
			}
		}
	}
}
